import SockJS from 'sockjs-client';
import Stomp from 'stompjs';

export class WebSocketClient {
  constructor(url, topic, callback) {
    this.url = url; // WebSocket 地址
    this.topic = topic; // 订阅的主题
    this.callback = callback; // 消息回调函数
    this.stompClient = null;
  }

  connect() {
    const socket = new SockJS(this.url);
    this.stompClient = Stomp.over(socket);

    this.stompClient.connect({}, () => {
      console.log('WebSocket connected');
      this.stompClient.subscribe(this.topic, (message) => {
        this.callback(message.body); // 收到消息时调用回调函数
      });
    }, (error) => {
      console.error('WebSocket connection error:', error);
      this.reconnect();
    });
  }

  disconnect() {
    if (this.stompClient) {
      this.stompClient.disconnect(() => {
        console.log('WebSocket disconnected');
      });
    }
  }

  reconnect() {
    setTimeout(() => {
      console.log('Reconnecting...');
      this.connect();
    }, 5000); // 5秒后重连
  }
}